package com.bdcom.planner;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bdcom.comp.CanvasPanel;
import com.bdcom.comp.InfoBarPanel;
import com.bdcom.comp.InspectorPanel;
import com.bdcom.comp.PropertyPanel;
import com.bdcom.comp.ToolBarPanel;
import com.bdcom.dialog.BarrierTypeCfgDialog;
import com.bdcom.dialog.DeviceTypeCfgDialog;
import com.bdcom.util.PlannerUtil;

/**
 * 应用程序主窗体
 * 
 * @author Administrator
 *
 */
@Component
public class ApplicationFrame extends JFrame implements ActionListener, WindowListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private InfoBarPanel infoBarPanel;
	@Autowired
	private InspectorPanel inspectorPanel;
	@Autowired
	private PropertyPanel propertyPanel;
	@Autowired
	private CanvasPanel canvasPanel;
	@Autowired
	private ToolBarPanel toolbarPanel;
	@Autowired
	private DeviceTypeCfgDialog deviceTypeCfgDialog;
	@Autowired
	private BarrierTypeCfgDialog barrierTypeCfgDialog;

	private static int frameWidth = 1024;

	private static int frameHeight = 768;

	private JFrame helpFrame;

	private Image image;

	private JSplitPane subSplit;

	private JSplitPane splitPanel;

	private JScrollPane canvasScroll;

	private static int x;

	public ApplicationFrame() throws HeadlessException {
		super();
		// TODO Auto-generated constructor stub
	}

	@PostConstruct
	private void init() throws IOException {

		// 初始化窗体尺寸
		initFrameSize();
		// 初始化菜单
		initMenubar();
		// 初始化状态栏
		initInfoPanel();
		// 初始化工具栏
		initToolBarPanel();
		// 初始化伸缩面板
		initSplitPanel();

		this.setLocationRelativeTo(null);

		this.setDefaultCloseOperation(EXIT_ON_CLOSE);

		image = ImageIO.read(new File("image/bdcom.png"));

		this.setIconImage(image);

		this.setVisible(true);

		this.addWindowListener(this);
	}

	private void initToolBarPanel() {
		// TODO Auto-generated method stub
		getContentPane().add(toolbarPanel, BorderLayout.NORTH);
	}

	private void initInfoPanel() {
		// TODO Auto-generated method stub

		getContentPane().add(infoBarPanel, BorderLayout.SOUTH);

	}

	private void initSplitPanel() {
		// TODO Auto-generated method stub
		splitPanel = new JSplitPane();

		splitPanel.setDividerLocation(110);

		initSubSplit();

		splitPanel.setLeftComponent(inspectorPanel);

		splitPanel.setRightComponent(subSplit);

		splitPanel.setOneTouchExpandable(true);

		getContentPane().add(splitPanel, BorderLayout.CENTER);
	}

	private void initSubSplit() {

		subSplit = new JSplitPane();

		canvasScroll = new JScrollPane(canvasPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

		canvasScroll.setMinimumSize(new Dimension(frameWidth - 400, frameHeight - 200));

		subSplit.setLeftComponent(canvasScroll);

		subSplit.setRightComponent(propertyPanel);

		subSplit.setOneTouchExpandable(true);

	}

	public void resizeScroll() {

		x = (x + 1) % 2;

		canvasScroll.setMinimumSize(new Dimension(frameWidth - 400 - x, frameHeight - 200 - x));

		subSplit.setLeftComponent(canvasScroll);

	}

	private void initFrameSize() {

		Toolkit defaultToolkit = Toolkit.getDefaultToolkit();

		Dimension screen = defaultToolkit.getScreenSize();

		Insets screenInsets = defaultToolkit.getScreenInsets(getGraphicsConfiguration());

		frameWidth = screen.width - screenInsets.left - screenInsets.right;

		frameHeight = screen.height - screenInsets.top - screenInsets.bottom;

		this.setSize(frameWidth, frameHeight);

		this.setTitle(PlannerUtil.getString("application_name"));
	}

	private void initMenubar() {

		JMenuBar menuBar = new JMenuBar();

		menuBar.setPreferredSize(new Dimension(0, 24));

		// 文件菜单
		JMenu menu = new JMenu(PlannerUtil.getString("file") + "(F)");

		menu.setMnemonic('F');

		menuBar.add(menu);
		// 新建子菜单
		JMenuItem miNew = new JMenuItem(PlannerUtil.getString("new"));

		miNew.setActionCommand(PlannerUtil.COMMAND_NEW_STR);

		miNew.setAccelerator(KeyStroke.getKeyStroke('N', java.awt.event.InputEvent.CTRL_DOWN_MASK));

		miNew.addActionListener(this);

		menu.add(miNew);
		// 保存子菜单
		JMenuItem miSave = new JMenuItem(PlannerUtil.getString("save"));

		miSave.setActionCommand(PlannerUtil.COMMAND_SAVE_FILE);

		miSave.setAccelerator(KeyStroke.getKeyStroke('S', java.awt.event.InputEvent.CTRL_DOWN_MASK));

		miSave.addActionListener(this);

		menu.add(miSave);
		// 删除子菜单
		JMenuItem miDel = new JMenuItem(PlannerUtil.getString("delete"));

		miDel.setActionCommand(PlannerUtil.COMMAND_DEL_FILE);

		miDel.setAccelerator(KeyStroke.getKeyStroke('D', java.awt.event.InputEvent.CTRL_DOWN_MASK));

		miDel.addActionListener(this);

		menu.add(miDel);
		// 菜单分割器
		JSeparator separator = new JSeparator();

		menu.add(separator);
		// 关闭子菜单
		JMenuItem miClose = new JMenuItem(PlannerUtil.getString("close"));

		miClose.setActionCommand(PlannerUtil.COMMAND_CLOSE_STR);

		miClose.setAccelerator(KeyStroke.getKeyStroke('W', java.awt.event.InputEvent.CTRL_DOWN_MASK));

		miClose.addActionListener(this);

		menu.add(miClose);
		// 配置菜单
		JMenu menu_cfg = new JMenu(PlannerUtil.getString("config") + "(C)");

		menu_cfg.setMnemonic('C');

		menuBar.add(menu_cfg);
		// 配置设备子菜单
		JMenuItem device_cfg = new JMenuItem(PlannerUtil.getString("deviceConfiguration"));

		device_cfg.setActionCommand(PlannerUtil.COMMAND_DEVICETYPE_CONFIG);

		device_cfg.setAccelerator(KeyStroke.getKeyStroke('F', java.awt.event.InputEvent.CTRL_DOWN_MASK));

		device_cfg.addActionListener(this);

		menu_cfg.add(device_cfg);
		// 配置障碍物子菜单
		JMenuItem barrier_cfg = new JMenuItem(PlannerUtil.getString("barrierConfiguration"));

		barrier_cfg.setActionCommand(PlannerUtil.COMMAND_BARRIER_CONFIG);

		barrier_cfg.setAccelerator(KeyStroke.getKeyStroke('B', java.awt.event.InputEvent.CTRL_DOWN_MASK));

		barrier_cfg.addActionListener(this);

		menu_cfg.add(barrier_cfg);
		// 帮助菜单
		JMenu menu_1 = new JMenu(PlannerUtil.getString("help") + "(H)");

		menu_1.setMnemonic('H');

		menuBar.add(menu_1);
		// 操作提示子菜单
		JMenuItem miGuider = new JMenuItem(PlannerUtil.getString("action_help"));

		miGuider.setActionCommand(PlannerUtil.COMMAND_HELP_STR);

		miGuider.setAccelerator(KeyStroke.getKeyStroke('H', java.awt.event.InputEvent.CTRL_DOWN_MASK));

		miGuider.addActionListener(this);

		menu_1.add(miGuider);

		setJMenuBar(menuBar);
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		String actionCommand = e.getActionCommand();

		if (actionCommand.equals(PlannerUtil.COMMAND_DEVICETYPE_CONFIG)) {
			deviceTypeCfgDialog.setVisible(true);
		} else if (actionCommand.equals(PlannerUtil.COMMAND_BARRIER_CONFIG)) {
			barrierTypeCfgDialog.setVisible(true);
		} else if (actionCommand.equals(PlannerUtil.COMMAND_NEW_STR)) {
			newModel();
		} else if (actionCommand.equals(PlannerUtil.COMMAND_DEL_FILE)) {
			deleteModel();
		} else if (actionCommand.equals(PlannerUtil.COMMAND_SAVE_FILE)) {
			saveModel();
		} else if (actionCommand.equals(PlannerUtil.COMMAND_CLOSE_STR)) {
			closeFrame();
		} else if (actionCommand.equals(PlannerUtil.COMMAND_HELP_STR)) {
			showHelpFrame();
		}

	}

	private void newModel() {
		// TODO Auto-generated method stub
		// 新建一个项目
		String projectName = JOptionPane.showInputDialog(this, PlannerUtil.getString("Please input projectName"));

		if (projectName == null || "".equals(projectName)) {
			// 名字输入错误
			return;
		}

		if (inspectorPanel.containsModel(projectName)) {

			JOptionPane.showMessageDialog(this, PlannerUtil.getString("Project name has already exists"));

			return;

		}

		try {
			inspectorPanel.addModel(projectName);
		} catch (Throwable e1) {
			// TODO Auto-generated catch block
			infoBarPanel.setInfo(PlannerUtil.getString("add faild"));
		}
	}

	// 删除模板
	private void deleteModel() {
		// TODO Auto-generated method stub
		int i = JOptionPane.showConfirmDialog(this, PlannerUtil.getString("Can not open it again,if you delete this project"),
				PlannerUtil.getString("Yes or No"), JOptionPane.OK_CANCEL_OPTION);

		if (i != JOptionPane.OK_OPTION) {
			return;
		}

		if (canvasPanel.getCanvasModel() == inspectorPanel.getSelectedModel()) {
			canvasPanel.setCanvasModel(null);
		}

		try {
			inspectorPanel.deleteModel();
		} catch (Throwable e1) {
			// TODO Auto-generated catch block
			infoBarPanel.setInfo(PlannerUtil.getString("delete faild"));
		}

	}

	// 保存模板
	private void saveModel() {
		// TODO Auto-generated method stub
		try {
			inspectorPanel.saveModel(canvasPanel.getCanvasModel());
		} catch (Throwable e1) {
			// TODO Auto-generated catch block
			infoBarPanel.setInfo(PlannerUtil.getString("save faild"));
		}
	}

	// 关闭程序
	private void closeFrame() {
		// TODO Auto-generated method stub
		if (JOptionPane.showConfirmDialog(null, PlannerUtil.getString("Only save current project's change automatically"),
				PlannerUtil.getString("Yes or No"), JOptionPane.YES_OPTION) == JOptionPane.OK_OPTION) {

			saveModel();

			this.dispose();

			System.exit(0);

		}
	}

	// 显示帮助文档
	private void showHelpFrame() {
		// TODO Auto-generated method stub
		if (helpFrame != null) {
			helpFrame.setState(JFrame.NORMAL);
			helpFrame.setVisible(true);
			return;
		}
		helpFrame = new JFrame();
		helpFrame.setIconImage(image);
		helpFrame.setSize(800, 600);
		helpFrame.setTitle(PlannerUtil.getString("help"));
		helpFrame.setLocationRelativeTo(null);
		helpFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		JEditorPane editorPane = new JEditorPane();
		editorPane.setEditable(false);
		JScrollPane scrollPane = new JScrollPane(editorPane);
		helpFrame.add(scrollPane);
		try {
			File hfile = new File("help.html");
			editorPane.setPage("file:///" + hfile.getAbsolutePath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			infoBarPanel.setInfo("get help file faild!");
			return;
		}
		helpFrame.setVisible(true);
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub

		saveModel();

	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

}
